
import { staticRouter, errorRouter } from "@/routers/modules/staticRouter";
import {
  getRouters
} from '@/api/menu'
import Layout from '@/layouts/index.vue'
import { defineStore, createPinia } from "pinia";
import { permissionState } from "@/store/interface";
export const PermissionStore = defineStore({
	// id: 必须的，在所有 Store 中唯一
	id: "PermissionStore",
	// state: 返回对象的函数
  state: (): permissionState => ({
    routes: [],
    addRoutes: [],
    defaultRoutes: [],
    topbarRouters: [],
    sidebarRouters: [],
    permissions: [],
  }),
  getters: {},
  actions: {
    // 生成路由
    async GenerateRoutes(postId: Number) {
      const { data } = await getRouters(postId)
      const sdata = JSON.parse(JSON.stringify(data.router))
      this.addRoutes = sdata
      this.routes = [...staticRouter,...errorRouter,...sdata]
      this.permissions = data.permissions
      const rewriteRoutes = filterAsyncRouter(sdata, false, false)
      // rewriteRoutes.push({ path: '*', redirect: '/404', hidden: true })
      return rewriteRoutes
    }
  }
});

// 引入 views 文件夹下所有 vue 文件
const modules = import.meta.glob("@/views/**/*.vue");
// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap: Menu.MenuOptions[], lastRouter = false, type = false) {
  return asyncRouterMap.filter(route => {
    if (type && route.children) {
      route.children = filterChildren(route.children)
    }
    if (route.component === 'Layout') {
      route.component = Layout
    }else if (route.component) {
      // route.component = loadView(route.component)
      route.component = modules["/src/views/" + route.component + ".vue"];
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, lastRouter, type)
    } else {
      delete route['children']
      delete route['redirect']
    }
    return true
  })
}

function filterChildren(childrenMap: Menu.MenuOptions[], lastRouter = false) {
  var children: Menu.MenuOptions[] = []
  childrenMap.forEach((el, index) => {
    if (el.children && el.children.length) {
      if (el.component === 'ParentView' && !lastRouter) {
        el.children.forEach(c => {
          c.path = el.path + '/' + c.path
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, lastRouter))
            return
          }
          children.push(c)
        })
        return
      }
    }
    children = children.concat(el)
  })
  return children
}

// 动态路由遍历，验证是否具备权限
// export function filterDynamicRoutes(routes: Menu.MenuOptions[]) {
//   const res = []
//   routes.forEach(route => {
//     if (route.permissions) {
//       if (auth.hasPermiOr(route.permissions)) {
//         res.push(route)
//       }
//     } else if (route.roles) {
//       if (auth.hasRoleOr(route.roles)) {
//         res.push(route)
//       }
//     }
//   })
//   return res
// }
interface WebpackRequire extends NodeRequire {
  ensure(
    dependencies: string[],
    callback: (require: WebpackRequire) => void,
    errorCallback?: (error: Error) => void,
    chunkName?: string
  ): void;
};

export const loadView = (view: any) : any=> {
  const require: WebpackRequire = (window as any).require;
  if (process.env.NODE_ENV === 'development') {
    return ()=> require.ensure([],require => require(`@/views/${view}`));
  } else {
    // 使用 import 实现生产环境的路由懒加载
    return ()=> require.ensure([],require => require(`@/views/${view}`));
  }
}